/**
 * download the nagios page
 * @param {String} hostgroup
 */
function theRequest(hostgroup) {
  var url = 'https://nagios/nagios/cgi-bin/status.cgi';
  var pars = 'hostgroup='+hostgroup;
  var myAjax = new Ajax.Request(
    url,
    {
      method: 'get',
      parameters: pars,
      onFailure: onActions.showFailure,
      onLoading: showLoader.loading,
      onComplete: onActions.showResponse
    });
}
/**
 * Check the daily backup
 */
backupRequestDay = function() {
  var url = 'https://nagios/proto/log/logday.txt';
  var pars = '';
   var myAjax = new Ajax.Request(
    url,
    {
      method: 'get',
      parameters: pars,
      onFailure: onActions.showFailure,
      onLoading: showLoader.loading,
      onComplete: onActions.backupResponse
    }
  );
}
/**
 * Check the weekly backup
 */
backupRequestWeek = function() {
  var url = 'https://nagios/proto/log/logweek.txt';
  var pars = '';
   var myAjax = new Ajax.Request(
    url,
    {
      method: 'get',
      parameters: pars,
      onFailure: onActions.showFailure,
      onLoading: showLoader.loading,
      onComplete: onActions.backupResponse
    }
  );
}
/**
 * Check the monthly backup
 */
backupRequestMonth = function() {
  var url = 'https://nagios/proto/log/logmonth.txt';
  var pars = '';
   var myAjax = new Ajax.Request(
    url,
    {
      method: 'get',
      parameters: pars,
      onFailure: onActions.showFailure,
      onLoading: showLoader.loading,
      onComplete: onActions.backupResponse
    }
  );
}
/**
 * Runs on request end and on error
 * @param {Object} originalRequest
 */
onActions = {
  showResponse: function(originalRequest) {
    prepareRequest(originalRequest.responseText);
  },

  showFailure: function() {
    alert('Request Error');
  },

  backupResponse: function(originalRequest) {
    backupPrepare(originalRequest.responseText);
  }

}

/**
 * replace the links
 * @param {Object} from
 * @param {Object} to
 */
function changeHref(from, to) {
  /*
  megvaltoztatja a linkek celjat betoltodes utan
  */
  var links = document.getElementsByTagName('a');
  var re = new RegExp(from);
  $A(links).each(function(link) {
    link.href = link.href.replace(re, to);
  });
  showLoader.done();
}
/**
 * display backup errors
 * @param {Object} req
 */
backupPrepare = function(req) {
  if(req != "") {
    var errors = '<table id="errorsTable">';
    errors += '<tr>';
    errors += '<td class="warning">';
    errors += req;
    errors += '</td>';
    errors += '</tr>';
    errors += '</table>';
    $('nagiosCont').innerHTML += errors;
  }
}
/**
 * process the received page, filters the errors and write these to the page
 * @param {Object} req
 */
function prepareRequest(req) {
  Element.update($('res_cont'), req);                                 // fill the testdiv with the response
  var nagiosTables = $A($('res_cont').getElementsByTagName('table')); // filter the tables into an array
  var tables = exploreTables.statusTables(nagiosTables);              // filter the tables with status class into an array
  var trs = exploreTables.statusTrs(tables);                          // filter the trs from the status tables into an array
  var tds = exploreTables.trTds(trs);                                 // filter the error cells

  if(tds.length>0) {
    var errors = '<table id="errorsTable">';
    tds.each(function(td) {
      errors += '<tr>';
      errors += td.parentNode.parentNode.parentNode.parentNode.childNodes[1].innerHTML;       // error container line
      errors += '</tr>';
    });
    errors += '</table>';
    $('nagiosCont').innerHTML += errors;                                        // display the errors
  }

  /*
  stop = speedTest.stop();                                                      // start speedtest
  speedTest.result(start,stop);                                                 // display speedtest
  */
}

/**
 * process the received tables, filters the errors
 * @param {Object} allTable
 */
exploreTables = {
  /**
   * filters the tables which have "status" class and push it into an array
   * @param {Object} allTable
   */
  statusTables: function(allTable) {
    var statusTables = Array();
    allTable.each(function(table) {
      if(Element.hasClassName(table, 'status')) {
        statusTables.push(table);
      }
    });
    return statusTables;
  },
  /**
   * Filters the tr-s into an array from the status tables
   * @param {Object} stTables
   */
  statusTrs: function(stTables) {
    var statusTrs = Array();
    stTables.each(function(table) {
      statusTrs.push(table.getElementsByTagName('tr'));
    });
    return statusTrs;
  },

  /**
   * filters the error cells
   * @param {Object} allTrs
   */
  trTds: function(allTrs) {
    var trTds = Array();
    var errorTrs = Array();
    allTrs.each(function(trs) {

      $A(trs).each(function(tr, trIndex) {

        trTables = tr.getElementsByTagName('table');
        $A(trTables).each(function(table, index) {

          tableTds = table.getElementsByTagName('td');
          $A(tableTds).each(function(td) {

            if(Element.hasClassName(td, "miniStatusCRITICAL")) {
              errorTrs.push(td.parentNode);
              index++;
            }
          });
        });
      });
    });
    return errorTrs;
  }

}
/**
 * show|hide the loader image
 */
showLoader = {
  loading: function() {
    Element.show($('loader'));
    Element.update($('loader'), '<img src="loading.gif" alt="Loading" />');
  },
  done: function() {
    Element.hide($('loader'));
  }
}

/**
 * displays the hostgroups
 */
function setNagiosValues() {
  var hostgroups = Array();
  hostgroups = $F('hostgroups').split(',');                                     // convert the input fileds value to array
  Element.update($('nagiosCont'), '');                                          // remove the content of the nagiosCont div
  hostgroups.each(function(dest) {                                              // checks the hostgroups and fill the errors into the nagioscont div
    theRequest(dest);
  });
  backupRequestDay();
  setTimeout("changeHref('^https://nagios/proto', 'https://nagios/nagios/cgi-bin')", "1000"); // replace the links
}
/**
 * speed test functions
 */
speedTest = {
  start: function() {
    var start = new Date();
    return start.getTime();
  },

  stop: function() {
    var stop = new Date();
    return stop.getTime();
  },

  result: function(start, stop) {
    var ido = stop-start;
    $('timer').innerHTML += ido+', ';
  }
}

/**
 * show|hide the input on the top of the page
 */
dhgr = {
  /*
  input rejto, mutato fuggvenyek
  */
  show: function() {
    /*
    megjeleniti a divet, inputot
    */
    if(Element.hasClassName($('hgr'), 'hgr_hide')) {
      Element.removeClassName($('hgr'), 'hgr_hide');
    }
    Element.addClassName($('hgr'), 'hgr_show');
    Element.show($('hostgroups'));
  },

  hide: function() {
    /*
    elrejti a divet, inputot
    */
    if(Element.hasClassName($('hgr'), 'hgr_show')) {
      Element.removeClassName($('hgr'), 'hgr_show');
    }
    Element.addClassName($('hgr'), 'hgr_hide');
    Element.hide($('hostgroups'));
  }

}
/**
 * observe the event handler functions to the input and divs
 */
initHgr = function() {
    Event.observe($('hostgroups'), 'mouseover', dhgr.show, false);
    Event.observe($('hostgroups'), 'mouseout', dhgr.show, false);

    Event.observe($('hgr'), 'mouseover', dhgr.show, false);
    Event.observe($('hgr'), 'click', dhgr.show, false);
    Event.observe($('hgr'), 'mouseout', dhgr.hide, false);
}
/**
 * initialization function
 */
function init() {
  /**
   * show loader
   */
  var globalHandlers = {
    onCreate: showLoader.loading
  };

  Ajax.Responders.register(globalHandlers);                                     // register event
  Element.hide($('res_cont'));                                                  // hide res_cont
  dhgr.hide();                                                                  // hide input field
  setNagiosValues();                                                            // start first request
  pe = new PeriodicalExecuter(setNagiosValues, 180);                            // send request peridocally
  initHgr();                                                                    // add input events
}

Event.observe(window, 'load', init, false);